package com.huangd.platform.modules.sys.service.impl;


import com.google.code.kaptcha.Producer;
import com.huangd.platform.common.exception.RRException;
import com.huangd.platform.modules.sys.service.SysCaptchaService;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

/**
 * 验证码
 *
 * @author huangd
 */
@Service("sysCaptchaService")
public class SysCaptchaServiceImpl  implements SysCaptchaService {
    @Resource
    private Producer producer;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public BufferedImage getCaptcha(String uuid) {

        if(StringUtils.isBlank(uuid)){
            throw new RRException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();
        String key = "dpzj:platfrom:captcha_code:" + uuid;

        redisTemplate.opsForValue().set(key, code, 60 * 5, TimeUnit.SECONDS);

        System.out.println(code);
        System.out.println(producer.toString());

        return producer.createImage(code);

    }

    @Override
    public boolean validate(String uuid, String code) {
        String key = "dpzj:platfrom:captcha_code:" + uuid;

        String redisCode = (String) redisTemplate.opsForValue().get(key);

        //删除验证码
        redisTemplate.delete(key);

        if (redisCode.equals(code)) {
            return true;
        }

        return false;
    }
}
